package top.malaoshi.webmvc.parameter;

import top.malaoshi.webmvc.info.MethodsArgumentInfo;
import top.malaoshi.webmvc.exception.RequestParamResolverException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 从request对象中取出参数，并放入 List（或List实现类） 的形参中
 * 如果形参是 List，默认使用 ArrayList 类
 */
public class ListResolver extends AbstractResolver implements RequestParamAndMethodArgsResolver {
    @Override
    public Object resolver(HttpServletRequest request, HttpServletResponse response , MethodsArgumentInfo mai) throws RequestParamResolverException {
        checkNameAndValue(mai);
        String parameterName = getName(mai);
        String[] parameterValues = request.getParameterValues(parameterName);
        Class type = mai.getType();
        List ret = null;
        if(parameterValues!=null) {
            int len = parameterValues.length;
            if(type == List.class || type == ArrayList.class) {
                ret = new ArrayList(len);
            }else{
                try {
                    ret = (List)type.newInstance();
                } catch (InstantiationException e) {
                    throw new RequestParamResolverException(e);
                } catch (IllegalAccessException e) {
                    throw new RequestParamResolverException(e);
                }
            }
//            Class generic = (Class) mai.getType().getGenericSuperclass();

            for (int i = 0; i < len; i++) {
                ret.add(parameterValues[i]);
            }
        }
        checkRequired(ret,mai);
        return ret;
    }
}
